package it.intecs.pisa.smarcos.activities;

import it.intecs.pisa.smarcos.R;
import it.intecs.pisa.smarcos.base.BeepManager;
import it.intecs.pisa.smarcos.base.GestureEvents;
import it.intecs.pisa.smarcos.base.GestureIntents;
import it.intecs.pisa.smarcos.base.SpeechManager;
import it.intecs.pisa.smarcos.util.MathUtils;
import it.intecs.pisa.smarcos.util.PatternUtils;

import java.util.ArrayList;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;


public class ModifyText extends BaseActivity {

	public static final String INTENT_SHOW="it.intecs.pisa.smarcos.activities.ModifyText.SHOW";
	private static final String TAG = ModifyText.class.getSimpleName();
	private static final String WORD = "Word";
	private static final String CHAR = "Char";

	private SpeechManager speechManager;

	// Common to all features
	View view; 
	private Vibrator vibrator;
	private ViewGroup baseCenterView;
	BeepManager beepManager;

	private String position;
	LayoutInflater inflater;

	IntentFilter resultFilter;
	private ReceiveFromKeyboard keyboardReceiver = null;
	
	private Boolean beepFlagDx = false;
	private Boolean beepFlagSx = false;
	private String what = WORD;
	private String originalText;
	private String char_;	
	private int currentPos = -1;
	private int posChar = -1;
	
	private ArrayList<String> scrollString;
	private String word; 
	float startX,startY;
	
	PatternUtils pattern;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Log.d(TAG, "OnCreate");

		speechManager = SpeechManager.getInstance(getApplicationContext());
		vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
		beepManager = BeepManager.getInstance(getApplicationContext());

		// Metodo di BaseViewManager
		Init(getBaseContext());
		inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
		view = inflater.inflate(R.layout.modify_text, null);
		setContentView(getBaseView());
		baseCenterView = (ViewGroup) findViewById(R.id.center_base_view);
		baseCenterView.addView(view);

		position = getString(R.string.MV_Modify_Text);

		Intent intent = getIntent();
		originalText = intent.getStringExtra("OriginalText");
		scrollString = intent.getStringArrayListExtra("ScrollText");
		Log.d(TAG, "text to modify " + originalText);
		
		pattern = new PatternUtils();
		
		// ResultReceiver filter
        resultFilter = new IntentFilter();
        resultFilter.addAction(ReceiveFromKeyboard.INTENT_SHOW);
        resultFilter.addCategory(Intent.CATEGORY_DEFAULT);
        keyboardReceiver = new ReceiveFromKeyboard();
        registerReceiver(keyboardReceiver, resultFilter);
	}


	@Override
	public void onResume() {
		super.onResume();

		Log.d(TAG, "onResume");
		passBy = false;	
		speechManager.say(R.string.TTS_Word_Scroll);		
	}


	@Override
	public void onDestroy() {
		super.onDestroy();
		unregisterReceiver(keyboardReceiver);
	}
		
	// CLOSE
	@Override
	public void onClick_A(){
		Log.d(TAG, "onClick_A");

		setResult(RESULT_CANCELED);
		sentResult = true;
		vibrator.vibrate(300);
		finish();
	}

	// POSITION
	@Override
	public void onClick_B(){
		Log.d(TAG, "onClick_B");
		if(position != null)
			speechManager.say(position, false, false);	
	}

	// REPEAT
	@Override
	public void onClick_C(){
		Log.d(TAG, "onClick_C");
		speechManager.sayPattern(word, false, false);
	}

	// DONE -> as CLOSE 
	@Override
	public void onClick_D(){
		Log.d(TAG, "onClick_D");

		vibrator.vibrate(300);
		if (what == CHAR){
			what = WORD;
			speechManager.say(R.string.TTS_Word_Scroll);
		}else{
			Intent data = new Intent();
			data.putExtra("ModifiedText", originalText);
			data.putStringArrayListExtra("ModifiedScrollText", scrollString);
			setResult(RESULT_OK, data);		
			sentResult = true;		
			finish();
		}
	}


	@Override
	public void onClick_Center(int event, float X, float Y){
		Log.d(TAG, "onClick_Center " + event);

		float lenghtTreshold=10;

		switch(event)
		{
		case GestureEvents.ONFLING_START:

			startX = X;
			startY = Y;
			break;

		case GestureEvents.ONFLING_STOP:

			float endX,endY;

			endX = X;
			endY = Y;

			float gestureLenght=0;

			gestureLenght=MathUtils.distanceBetweenPoints(endX,startX,endY,startY);

			if(gestureLenght>lenghtTreshold){

				String gesture = MathUtils.calculateSlice(endX,startX,endY,startY);
				if (gesture.length() != 0)
					ModifyTextHandling(gesture);
			}
			break;

		case GestureEvents.ONDOUBLETAP:
			ModifyTextHandling(GestureIntents.INTENT_GESTURE_SELECT);
			break;

		case GestureEvents.ONSCROLL:
			if (passBy == true)
				speechManager.say(position, false, false);
			break;
		}
	}

	
	
	
	private void ModifyTextHandling(String intAction) 	{

		Log.d(TAG, "ModifyTextHandling " + intAction);
		
		TextView text = (TextView) findViewById(R.id.ModifyText);

		if (intAction.equals(GestureIntents.INTENT_GESTURE_SELECT)) {

			beepFlagDx = false;
			beepFlagSx = false;
			if (what == WORD){
				what = CHAR;
				if (word.length() > 1){
					posChar = -1;
					speechManager.say(R.string.TTS_Char_Scroll);
					return;
				}else
					posChar = 0;
			}
			
			if (what == CHAR){		
				Intent intent;
				intent=new Intent(Keyboards.INTENT_SHOW);
				intent.addCategory(Intent.CATEGORY_DEFAULT);
				intent.putExtra("whereReturn", "it.intecs.pisa.smarcos.services.ReceiveFromKeyboard.SHOW");
				intent.putExtra("keyboardType", "QWERTY_KEYBOARD_NO_MODIFY");
				intent.putExtra("messageToSay", getString(R.string.TTS_Char_Modify));
				startActivity(intent);		
			}
		}
		else {
			if (intAction.equals(GestureIntents.INTENT_GESTURE_RIGHT)){

				if (what == WORD){
					if ((currentPos == scrollString.size() - 1)  && beepFlagSx == false){
						beepManager.playBeepSound();
						beepFlagDx = true;
						return;
					}
					
					if ((beepFlagSx == false) || currentPos == -1)
						currentPos++;
					beepFlagSx = false;
					word = scrollString.get(currentPos);
					if (!word.equals(" ")){
						text.setText(word);
						speechManager.sayPattern(word, false, false);
					}else
						ModifyTextHandling(intAction);
				}
				if (what == CHAR){
					if (posChar == word.length() - 1){
						beepFlagDx = true;
						beepManager.playBeepSound();
						return;
					}

					if ((beepFlagSx == false) || posChar == -1)
						posChar++;
					beepFlagSx = false;
					char_ = word.substring(posChar, posChar + 1);
					text.setText(char_);
					speechManager.sayPattern(char_, false, false);
				}	
			}
			else if(intAction.equals(GestureIntents.INTENT_GESTURE_LEFT)){

				if (what == WORD){
					
					if ((currentPos == 0 || currentPos == -1) && beepFlagDx == false){
						beepManager.playBeepSound();
						beepFlagSx = true;
						return;
					}
					
					if (beepFlagDx == false)
						currentPos--;
					else beepFlagDx = false;
					word = scrollString.get(currentPos);
					if (!word.equals(" ")){
						text.setText(word);
						speechManager.sayPattern(word, false, false);
					}else
						ModifyTextHandling(intAction);
				}

				if (what == CHAR){
					if ((posChar == 0) || (posChar == -1)){
						beepFlagSx = true;
						beepManager.playBeepSound();
						return;
					}
					
					if (beepFlagDx == false)
						posChar--;
					else beepFlagDx = false;	
					char_ = word.substring(posChar, posChar + 1);
					text.setText(char_);
					speechManager.sayPattern(char_, false, false);
				}
			} 		
		}
	}

	public class ReceiveFromKeyboard extends BroadcastReceiver {

		public static final String INTENT_SHOW="it.intecs.pisa.smarcos.services.ReceiveFromKeyboard.SHOW";
		private final String TAG = ReceiveFromKeyboard.class.getSimpleName();

		@Override
		public void onReceive(Context arg0, Intent intent) {

			int i;
			//String change;
			String result = intent.getStringExtra("Result");
			Log.d(TAG, "OnReceive - text to insert " + result);
			Log.d(TAG, "OnReceive - currentPos " + currentPos + " posChar " + posChar);

			if (result.length() == 0 || !result.equals("NORESULT")) { 
				
				if (result.equals("DEL CHAR"))
					result = "";
				
				originalText = "";
				
				for (i=0; i<currentPos; i++)
					originalText += scrollString.get(i);
				
				if (posChar > 0){ 			
					originalText += scrollString.get(currentPos).substring(0, posChar) + result;
					//change = scrollString.get(currentPos).substring(0, posChar) + result;
				}else{
					originalText += result;
					//change = result;
				}

				if (result.equals("")){
					if (posChar < scrollString.get(currentPos).length() - 1){	
						originalText += scrollString.get(currentPos).substring(posChar+1);
						//change += scrollString.get(currentPos).substring(posChar+1);
					}
				}else{
					if (posChar <= scrollString.get(currentPos).length() - 1){	
						originalText += scrollString.get(currentPos).substring(posChar);
						//change += scrollString.get(currentPos).substring(posChar);
					}
				}

				for (i=currentPos+1; i<scrollString.size(); i++)
					originalText += scrollString.get(i);

				//scrollString.set(currentPos, change);
				
				scrollString = pattern.Split(originalText);
				
				currentPos = -1;
				posChar = -1;
				what = WORD;
			}
		}		
	}
}


